import { getGoodsPage, GoodsUpdateDTO, GoodsVO, removeGoods, saveGoods, updateGoods } from '@/services/GoodsService'
import { EditableProTable, ProColumns } from '@ant-design/pro-components'
import { RecordKey } from '@ant-design/pro-utils/es/useEditableArray'
import { useModel } from '@umijs/max'
import { Button, message } from 'antd'

const GoodsSetting = () => {
  let { getDictEnum } = useModel('dict')

  const columns: ProColumns<GoodsVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      hideInTable: true,
    },
    {
      title: '套系类型',
      dataIndex: 'goodsType',
      valueEnum: getDictEnum('goods_type'),
      editable: () => true,
    },
    {
      title: '套系名称',
      dataIndex: 'goodsName',
      editable: () => true,
    },
    {
      title: '套系描述',
      dataIndex: 'goodsDesc',
      editable: () => true,
    },
    {
      title: '套系价格',
      valueType: 'money',
      dataIndex: 'price',
      editable: () => true,
      renderText: (text) => text / 100,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <Button key={record.id} type="link" onClick={() => action?.startEditable?.(record.id)}>
          编辑
        </Button>,
      ],
    },
  ]

  return (
    <>
      <EditableProTable<GoodsVO>
        rowKey="id"
        columns={columns}
        request={async () => getGoodsPage({ current: 1, size: 500 })}
        recordCreatorProps={{
          // 每次新增的时候需要Key
          record: () => ({ id: `-${Math.random().toFixed(0)}` } as GoodsVO),
          creatorButtonText: '新增套系',
        }}
        editable={{
          onSave: async (key: RecordKey, record: GoodsVO) => {
            let dto: GoodsUpdateDTO = JSON.parse(JSON.stringify(record))
            record.price = record.price * 100
            dto.price = dto.price * 100
            if (dto.id?.startsWith('-')) {
              dto.id = undefined
              saveGoods(dto).then(message.success('添加成功'))
              return true
            }
            updateGoods(dto).then(message.success('更新成功'))
            return true
          },
          onDelete: async (key: RecordKey, record: GoodsVO) => {
            removeGoods(record.id).then(message.success('删除成功'))
            return true
          },
        }}
      />
    </>
  )
}

export default GoodsSetting
